package utils

import (
	"errors"
	"time"
)

const (
	LAYOUT_FORMAT19 = "2006-01-02 15:04:05"
	LAYOUT_FORMAT10 = "2006-01-02"
	LAYOUT_FORMAT8  = "20060102"
)

var (
	loc, _ = time.LoadLocation("Asia/Chongqing")
)

// GetNowTime get current time
func GetNowTime() time.Time {
	return time.Now()
}

// GetNowTimestamp get current timestamp
func GetNowTimestamp() int {
	return int(GetNowTime().Unix())
}

func GetNowTimestamp13() int {
	return int(GetNowTime().UnixNano() / 1e6)
}

// Format19 format date YYYY-MM-DD HH:mm:ss
func Format19(time time.Time) string {
	return time.Format(LAYOUT_FORMAT19)
}

// Format10 format date YYYY-MM-DD
func Format10(time time.Time) string {
	return time.Format(LAYOUT_FORMAT10)
}

// Format8 format date YYYYMMDD
func Format8(time time.Time) string {
	return time.Format(LAYOUT_FORMAT8)
}

// TimeIntervalDay 计算两个时间相隔多少天
func TimeIntervalDay(t1, t2 time.Time) int {
	t1 = t1.UTC().Truncate(24 * time.Hour)
	t2 = t2.UTC().Truncate(24 * time.Hour)
	result := int(t1.Sub(t2).Hours() / 24)
	if result < 0 {
		result *= -1
	}
	return result
}

// TimeIntervalSecond 两个时间相隔秒数
func TimeIntervalSecond(time1 time.Time, time2 time.Time) int {
	d := time2.Sub(time1)
	return int(d / 1e9)
}

// Format19ToTimestamp 格式化的时间(YYYY-MM-DD HH:mm:ss)转时间戳
func Format19ToTimestamp(formatTime string) (int, error) {
	if len(formatTime) != 19 {
		return 0, errors.New("formatTime length error")
	} else {
		sTemp, err := time.ParseInLocation(LAYOUT_FORMAT19, formatTime, loc)
		if err != nil {
			return 0, err
		}
		return int(sTemp.Unix()), nil
	}
}

// Format10ToTimestamp 格式化的时间(YYYY-MM-DD)转时间戳
func Format10ToTimestamp(formatTime string) (int, error) {
	if len(formatTime) != 10 {
		return 0, errors.New("formatTime length error")
	} else {
		sTemp, err := time.ParseInLocation(LAYOUT_FORMAT10, formatTime, loc)
		if err != nil {
			return 0, err
		}
		return int(sTemp.Unix()), nil
	}
}

// Format8ToTimestamp 格式化的时间(YYYYMMDD)转时间戳
func Format8ToTimestamp(formatTime string) (int, error) {
	if len(formatTime) != 10 {
		return 0, errors.New("formatTime length error")
	} else {
		sTemp, err := time.ParseInLocation(LAYOUT_FORMAT8, formatTime, loc)
		if err != nil {
			return 0, err
		}
		return int(sTemp.Unix()), nil
	}
}
